// @system GO-CRAWL <shop-yun.com>
// @version go-crawl 1.0
// @author xiaotangren  <unphp@qq.com>
// @data 2014-07-29
//

package bsc_websocket

import (
	"code.google.com/p/go.net/websocket"
	"fmt"
	"net/http"
	base "shop-yun.go/go-crawl/utils/base"
	"strconv"
	"time"
)

func NewWebsocketServer(port string, safelog base.InterfaceSafeLog) *websocketServer {
	return &websocketServer{
		port:    port,
		safeLog: safelog,
	}
}

type websocketServer struct {
	port    string
	safeLog base.InterfaceSafeLog
}

func (this *websocketServer) Run() {
	this.safeLog.Create()
	this.safeLog.Add("ListenAndServe run, port：" + this.port)
	http.Handle("/", websocket.Handler(this.putImg))
	http.HandleFunc("/log", this.log)
	if err := http.ListenAndServe(":"+this.port, nil); err != nil {
		this.safeLog.Add("ListenAndServe run fail!")
	} //此时已经在监听

}

func (this *websocketServer) putImg(ws *websocket.Conn) {

}

func (this *websocketServer) log(w http.ResponseWriter, r *http.Request) {
	msg := ""
	msg = time.Now().String()
	if s, b := this.safeLog.Find(); b {
		//data, _ := s.(Pub.StackChaner).Get() //s实际上是conf.myTempChan类型，conf.myTempChan实现了Pub.StackChaner接口

		i := 1
		for _, v := range s {
			msg = msg + "<br>\r\n <span>" + strconv.Itoa(i) + ".</span>&nbsp;&nbsp;&nbsp;" + v
			i++
		}
	} else {
		msg = "Error! "
	}
	w.Header().Set("content-type", "text/html; charset=utf-8")
	w.Header().Set("X-Powered-By", "PHP/6.0")
	w.Header().Set("Server", "不告诉你！")
	fmt.Fprintln(w, msg)
}
